/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.vdialog.view.template;

import offset.nodes.client.view.MappedSchemaNodeRenderer;
import offset.nodes.client.view.TreeNodeChooserDialog;
import java.awt.CardLayout;
import javax.jcr.PropertyType;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import offset.nodes.Constants;
import offset.nodes.client.chooser.view.TypeChooserDialog;
import offset.nodes.client.vdialog.model.template.AbstractTemplateNode;
import offset.nodes.client.model.HierarchyTree;
import offset.nodes.client.model.NodeTypes;
import offset.nodes.client.vdialog.model.template.PathNode;
import offset.nodes.client.virtual.model.SchemaNode;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.model.Server;
import offset.nodes.client.tree.model.TreeNodePanel;
import offset.nodes.client.tree.model.TreeNodePanelContainer;
import offset.nodes.client.model.TreeNodeUserObject;
import offset.nodes.client.virtual.model.jcr.QName;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeDefinition;
import offset.nodes.client.virtual.model.jcr.nodetype.PropertyDefinition;

/**
 *
 * @author  Walter Lütgenau
 */
public class FolderPanel extends javax.swing.JPanel implements TreeNodePanel {

    class TextFieldDocumentListener implements DocumentListener {

        public void changedUpdate(DocumentEvent e) {
            validateOkButton();
        }

        public void insertUpdate(DocumentEvent e) {
            validateOkButton();
        }

        public void removeUpdate(DocumentEvent e) {
            validateOkButton();
        }
    }
    TreeNodePanelContainer container = null;
    SimpleNamespaceRegistry namespaces = SimpleNamespaceRegistry.getInstance();
    TypeChooserDialog newTypeChooser = null;
    Server server;
    TextFieldDocumentListener textFieldDocumentListener = new TextFieldDocumentListener();
    TreeNodeUserObject userObject;
    NodeTypes types = null;
    String pathNodeType;

    /** Creates new form FolderPanel
     * @param server the server model
     * @param types the node types repository
     */
    public FolderPanel(Server server, NodeTypes types, String pathNodeType) {
        this.server = server;
        this.types = types;
        this.pathNodeType = pathNodeType;
        initComponents();
    }

    protected void validateExtendButton() {
        TreePath selected = container.getTree().getSelectionModel().getSelectionPath();
        if (selected == null) {
            return;
        }

        selected = selected.getParentPath();
        while (selected != null) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) selected.getLastPathComponent();
            AbstractTemplateNode userObject = (AbstractTemplateNode) node.getUserObject();
            if (userObject.getNodeType() != null) {
                extendButton.setEnabled(true);
                return;
            }

            selected = selected.getParentPath();
        }

        extendButton.setEnabled(false);
    }

    private void validateOkButton() {
        boolean ok = true;
        if (typeTextField.getText() == null || typeTextField.getText().length() == 0) {
            ok = false;
        }
        if (pathTextRadio.isSelected() && (pathnameTextField.getText() == null || pathnameTextField.getText().length() == 0)) {
            ok = false;
        } else if (pathPropertyRadio.isSelected() && folderPropertyCombo.getItemCount() == 0) {
            ok = false;
        }

        container.enableOkButton(ok);
    }

    protected void setPath(PathNode definition) {
        if (definition.getQuery() != null) {
            typeTextField.setText(definition.getQuery());
        } else {
            typeTextField.setText("");
        }

        if (definition.getName() != null && definition.getName().length() > 0) {
            pathnameTextField.setText(definition.getName());
            pathTextRadio.setSelected(true);
            pathPropertyRadio.setSelected(false);
            ((CardLayout) namePanel.getLayout()).show(namePanel, "text");
        } else if (definition.getNameProperty() != null) {
            folderPropertyCombo.setSelectedItem(definition.getNameProperty());
            pathTextRadio.setSelected(false);
            pathPropertyRadio.setSelected(true);
            ((CardLayout) namePanel.getLayout()).show(namePanel, "property");
        } else {
            pathnameTextField.setText(definition.getName());
            pathTextRadio.setSelected(true);
            pathPropertyRadio.setSelected(false);
            ((CardLayout) namePanel.getLayout()).show(namePanel, "text");
        }

        validateExtendButton();
        validateOkButton();
    }

    protected PathNode getPath() {
        PathNode folder = new PathNode(pathNodeType);

        folder.setQuery(typeTextField.getText());

        if (pathTextRadio.isSelected()) {
            folder.setName(pathnameTextField.getText());
        } else if (pathPropertyRadio.isSelected()) {
            folder.setNameProperty((String) folderPropertyCombo.getSelectedItem());
        }

        NodeTypeDefinition definition = types.get(QName.valueOf(namespaces.toQNameString(folder.getSchemaPath())));
        folder.setNodeType(definition);

        return folder;
    }

    protected void setProperties(PropertyDefinition[] properties) {
        folderPropertyCombo.removeAllItems();

        for (int i = 0; i < properties.length; i++) {
            if (properties[i].getRequiredType() == PropertyType.NAME ||
                    properties[i].getRequiredType() == PropertyType.PATH ||
                    properties[i].getRequiredType() == PropertyType.STRING) {
                folderPropertyCombo.addItem(namespaces.toPrefixName(properties[i].getName()));
            }

        }
    }

    protected String[] toStringArray(TreePath path) {
        String[] names = new String[path.getPathCount()];
        int i = 0;
        while (path != null) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            if (node.getUserObject() != null && node.getUserObject() instanceof AbstractTemplateNode) {
                AbstractTemplateNode userObject = (AbstractTemplateNode) node.getUserObject();
                names[i++] = userObject.getSchemaPath();
            }

            path = path.getParentPath();
        }

        return names;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        folderNameButtonGroup = new javax.swing.ButtonGroup();
        typeLabel = new javax.swing.JLabel();
        typeTextField = new javax.swing.JTextField();
        typeTextField.getDocument().addDocumentListener(textFieldDocumentListener);
        extendButton = new javax.swing.JButton();
        newButton = new javax.swing.JButton();
        namePathLabel = new javax.swing.JLabel();
        pathTextRadio = new javax.swing.JRadioButton();
        pathPropertyRadio = new javax.swing.JRadioButton();
        namePanel = new javax.swing.JPanel();
        textPanel = new javax.swing.JPanel();
        pathnameTextField = new javax.swing.JTextField();
        pathnameTextField.getDocument().addDocumentListener(textFieldDocumentListener);
        propertyPanel = new javax.swing.JPanel();
        folderPropertyCombo = new javax.swing.JComboBox();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("offset/nodes/client/vdialog/view/DialogBundle"); // NOI18N
        typeLabel.setText(bundle.getString("template.templatePanel.query")); // NOI18N

        extendButton.setText(bundle.getString("template.templatePanel.extendQuery")); // NOI18N
        extendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectExtendedType(evt);
            }
        });

        newButton.setText(bundle.getString("template.templatePanel.newQuery")); // NOI18N
        newButton.setPreferredSize(new java.awt.Dimension(67, 23));
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectNewType(evt);
            }
        });

        namePathLabel.setText(bundle.getString("template.folderPanel.name")); // NOI18N

        folderNameButtonGroup.add(pathTextRadio);
        pathTextRadio.setSelected(true);
        pathTextRadio.setText(bundle.getString("template.folderPanel.text")); // NOI18N
        pathTextRadio.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        pathTextRadio.setMargin(new java.awt.Insets(0, 0, 0, 0));
        pathTextRadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setNameFromText(evt);
            }
        });

        folderNameButtonGroup.add(pathPropertyRadio);
        pathPropertyRadio.setText(bundle.getString("template.folderPanel.property")); // NOI18N
        pathPropertyRadio.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        pathPropertyRadio.setMargin(new java.awt.Insets(0, 0, 0, 0));
        pathPropertyRadio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setNameFromProperty(evt);
            }
        });

        namePanel.setLayout(new java.awt.CardLayout());

        pathnameTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                validatePathName(evt);
            }
        });

        javax.swing.GroupLayout textPanelLayout = new javax.swing.GroupLayout(textPanel);
        textPanel.setLayout(textPanelLayout);
        textPanelLayout.setHorizontalGroup(
            textPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pathnameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE)
        );
        textPanelLayout.setVerticalGroup(
            textPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(textPanelLayout.createSequentialGroup()
                .addComponent(pathnameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(72, Short.MAX_VALUE))
        );

        namePanel.add(textPanel, "text");

        folderPropertyCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout propertyPanelLayout = new javax.swing.GroupLayout(propertyPanel);
        propertyPanel.setLayout(propertyPanelLayout);
        propertyPanelLayout.setHorizontalGroup(
            propertyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(folderPropertyCombo, 0, 437, Short.MAX_VALUE)
        );
        propertyPanelLayout.setVerticalGroup(
            propertyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(propertyPanelLayout.createSequentialGroup()
                .addComponent(folderPropertyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(70, Short.MAX_VALUE))
        );

        namePanel.add(propertyPanel, "property");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addComponent(namePanel, 0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(typeLabel)
                                .addGap(47, 47, 47)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(typeTextField)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(extendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(namePathLabel)
                                .addGap(46, 46, 46)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(pathTextRadio)
                                    .addComponent(pathPropertyRadio))))))
                .addGap(66, 66, 66))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(typeLabel)
                    .addComponent(typeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(extendButton))
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pathTextRadio)
                    .addComponent(namePathLabel))
                .addGap(16, 16, 16)
                .addComponent(pathPropertyRadio)
                .addGap(18, 18, 18)
                .addComponent(namePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    private void selectExtendedType(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectExtendedType
        TreePath path = container.getTree().getSelectionModel().getSelectionPath();
        path = path.getParentPath();
        String[] mappedPathes = toStringArray(path);
        AbstractTemplateNode userObject = null;

        while (path != null) {
            DefaultMutableTreeNode current = (DefaultMutableTreeNode) path.getLastPathComponent();
            userObject = (AbstractTemplateNode) current.getUserObject();

            if (userObject == null) // reached root without finding base query. Something wrong here, return
                return;

            if (userObject.getQuery() != null && userObject.getQuery().indexOf("/") < 0) // found base query
                 break;
 
            path = path.getParentPath();
        }

        DefaultMutableTreeNode querySchemaNode = HierarchyTree.setupHierarchicalTree(userObject.getNodeType().getName(), userObject.getNodeType(), null, types, false, false);
        TreeNodeChooserDialog chooser = new TreeNodeChooserDialog(null, true, querySchemaNode);
        chooser.setCellRenderer(new MappedSchemaNodeRenderer(mappedPathes));
        chooser.setVisible(true);
        if (chooser.getReturnStatus() == TreeNodeChooserDialog.RET_OK) {
            DefaultMutableTreeNode selected = chooser.getSelectedNode();
            typeTextField.setText(getExtendedPath(querySchemaNode, selected, mappedPathes));
            setProperties(((SchemaNode) selected.getUserObject()).getNodeType().getDeclaredPropertyDefinitions());
        }
 
}//GEN-LAST:event_selectExtendedType
    
    /**
     * Determine the query string from the selected schema node
     * 
     * @param schema the schema nodes displayed to the user
     * @param selected the schema node selected by the user
     * @param mappedPathes a string array of pathnames of the parent nodes of the current virtual folder/page/template
     * @return the query string
     */
    protected String getExtendedPath(DefaultMutableTreeNode schema, DefaultMutableTreeNode selected, String[] mappedPathes) {
        StringBuffer result = new StringBuffer();
        StringBuffer path = new StringBuffer();
        
        while( schema != null ) {
            if ( path.length() > 0)
                path.append("/");
            path.append(schema.toString());
            boolean isMapped = false;
            
            for( int i=0; i<mappedPathes.length; i++) {
                if ( path.toString().equals(mappedPathes[i])) {
                    isMapped = true;
                    break;
                }
            }
            
            if ( isMapped) {
                result = new StringBuffer(schema.toString());
                result.append("[ancestor()]");
            }
            else
                result.append("/"+schema.toString());
            
            if ( schema == selected )
                break;
            
            if ( schema.getChildCount() > 0) 
                schema = (DefaultMutableTreeNode) schema.getChildAt(0);
            else
                schema = null;
        }
        
        return result.toString();
    }
    
    private void selectNewType(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectNewType
        if (newTypeChooser == null) {
            newTypeChooser = new TypeChooserDialog(null, true, server, new QName(Constants.URI_NODES_DATA, ""));
        }
        newTypeChooser.setVisible(true);
        if (newTypeChooser.getReturnStatus() == TypeChooserDialog.RET_OK) {
            typeTextField.setText(namespaces.toPrefixName(newTypeChooser.getDefinition().getName()));
            setProperties(newTypeChooser.getDefinition().getDeclaredPropertyDefinitions());

            validateOkButton();
        }
}//GEN-LAST:event_selectNewType

    private void setNameFromText(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setNameFromText
        ((CardLayout) namePanel.getLayout()).show(namePanel, "text");
        validateOkButton();
}//GEN-LAST:event_setNameFromText

    private void setNameFromProperty(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setNameFromProperty
        ((CardLayout) namePanel.getLayout()).show(namePanel, "property");
        validateOkButton();
}//GEN-LAST:event_setNameFromProperty

    private void validatePathName(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_validatePathName
    // TODO add your handling code here:
}//GEN-LAST:event_validatePathName
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton extendButton;
    private javax.swing.ButtonGroup folderNameButtonGroup;
    private javax.swing.JComboBox folderPropertyCombo;
    private javax.swing.JPanel namePanel;
    private javax.swing.JLabel namePathLabel;
    private javax.swing.JButton newButton;
    private javax.swing.JRadioButton pathPropertyRadio;
    private javax.swing.JRadioButton pathTextRadio;
    private javax.swing.JTextField pathnameTextField;
    private javax.swing.JPanel propertyPanel;
    private javax.swing.JPanel textPanel;
    private javax.swing.JLabel typeLabel;
    private javax.swing.JTextField typeTextField;
    // End of variables declaration//GEN-END:variables
    public void setPanel(TreeNodeUserObject userObject) {
        this.userObject = userObject;
        if ( userObject != null && userObject instanceof PathNode)
            setPath((PathNode) userObject);
    }

    public TreeNodeUserObject getUserObject() {
        return getPath();
    }

    public void setContainer(TreeNodePanelContainer container) {
        this.container = container;
    }
}
